package com.dubbo.service.impl;

import com.alibaba.fastjson.JSON;
import com.dubbo.common.MathUtils;
import com.dubbo.common.ResponseUtil;
import com.dubbo.common.check.CheckUtil;
import com.dubbo.common.number.NumberUtils;
import com.dubbo.common.page.PageResponse;
import com.dubbo.common.page.PageUtils;
import com.dubbo.common.push.JpushClientUtil;
import com.dubbo.domain.*;
import com.dubbo.domain.Process;
import com.dubbo.domain.info.ResultMessage;
import com.dubbo.mapper.*;
import com.dubbo.service.business.placeOrder.PlaceOrderService;
import com.dubbo.service.impl.base.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 下单ServiceImpl
 * @author wujunyuan
 * @date 2018年12月15日  上午11:13:57
 */
@Service
@Transactional(readOnly=false,rollbackFor=Exception.class)
public class PlaceOrderServiceImpl extends BaseServiceImpl<Goods> implements PlaceOrderService {
	@Autowired
	private GoodsMapper goodsMapper;
	@Autowired
	private CategoryMapper categoryMapper;
	@Autowired 
	private ShoppingcartMapper shoppingcartMapper;
	/*@Autowired
	private DictMapper dictMapper;*/
	@Autowired 
	private OrderMapper orderMapper;
	@Autowired
	private ShippingMapper shoppingMapper;
	@Autowired
	private AddressMapper addressMapper;
	@Autowired
	private OrderItemMapper orderItemMapper;
	@Autowired
	private ProcessMapper processMapper;
	@Autowired
	private URoleLevelMapper uRoleLevelMapper;
	@Autowired
	private ORoleLevelMapper oRoleLevelMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private QuartzMapper quartzMapper;
	@Value("${fastdfsUrl}")
	private String fastdfsUrl;
	@Autowired
	private MessageMapper messageMapper;
	@Autowired
	private CategoryRatioMapper categoryRatioMapper;
	
	/**
	 * 获取下单首页一级系列数据
	 * @author wujunyuan
	 * @date 2018年12月26日  下午5:20:42
	 * @param user
	 * @param pageStart
	 * @param pageTotal
	 * @return
	 */
	@Override
	public Map<String, Object> findCategoryPlaceOrder() {
		//获取一级系列
		List<Map<String,Object>> result = categoryMapper.findCategoryParentListNotLimit();
		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK, result);
	}
	
	/**
	 * 根据一级系列id获取下单首页二级系列数据
	 * @author wujunyuan
	 * @date 2019年1月14日 上午10:35:15
	 * @param categoryId
	 * @return
	 */
	@Override
	public Map<String, Object> findCategoryPlaceOrder2(Long categoryId) {
		if (categoryId == null || categoryId < 0) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_ERROR, "categoryId error");
		}
		//获取二级系列
		List<Map<String,Object>> result = categoryMapper.findCategoryList(categoryId);
		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK, result);
	}

	/**
	 * 获取下单首页商品数据
	 * @author wujunyuan
	 * @date 2018年12月26日 下午5:21:42
	 * @param request
	 * @param categoryId
	 * @return
	 * @throws Exception
	 */
	@Override
	public Map<String, Object> findGoodsPlaceOrder(User user, Long categoryId,Long pageStart,Long pageTotal) {
		if (categoryId == null || categoryId < 0) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_ERROR, "categoryId error");
		}
		pageStart = PageUtils.initialPageStart(pageStart);
		pageTotal = PageUtils.packagePageTotal(pageTotal, 5, 10);
		// 页面数据结果集
		Map<String, Object> resultMap = new HashMap<>();
		// 获取该系列的配图
		List<Map<String, Object>> picList = categoryMapper.findCategoryPicList(categoryId);
		if (!picList.isEmpty()) {
			// 处理图片
			for (Map<String, Object> map : picList) {
				Object pic = map.get("url");
				if (pic != null && StringUtils.isNotBlank(pic.toString())) {
					String picUrl = this.getPic(pic.toString());
					map.put("url", picUrl);
				}
			}
		}
		// 系列的配图
		resultMap.put("categoryPic", picList);
		//查询与该系列对应的商品总数
		Long pageCount = goodsMapper.findMatchCategorCount(categoryId);
		// 查询与该系列对应的商品列表
		List<Map<String, Object>> goodsList = goodsMapper.findMatchCategor(categoryId,
				PageUtils.countPageStart(pageStart, pageTotal),pageTotal);
		if (goodsList != null && !goodsList.isEmpty()) {
			for (Map<String, Object> map : goodsList) {
				// 普通用户无权限查看价格
				if (user==null||user.getType() == 0) {
					map.put("price", "无权限查看价格");
				} else {
					Object price = map.get("price");
					if (price != null && StringUtils.isNotBlank(price.toString())) {
						map.put("price", map.get("price"));
					}
				}
				// 处理图片
				Object pic = map.get("pic");
				if (pic != null && StringUtils.isNotBlank(pic.toString())) {
					// logo
					map.put("pic", this.getPic(pic.toString()));
				}
				Object content = map.get("content");
				if (content != null && StringUtils.isNotBlank(content.toString())) {
					// 弹窗规格详情图
					map.put("content", this.getPic(content.toString()));
				}
				//前端大佬要求返回
				map.put("count", "0");
			}
		}
		// 商品列表
		resultMap.put("goodsList",new PageResponse(pageStart, pageTotal, pageCount, goodsList));
		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK, resultMap);
	}


	/**
	 * 拼接图片域名
	 * @author gujiahua
	 * 2018年11月28日 上午11:28:03
	 * @param pic
	 * @return
	 */
	private String getPic(String pic){
		if(!CheckUtil.checkUrl(pic)){
			pic =  fastdfsUrl+pic;
		}
		return pic;
	}


	/**
	 * 添加购物车
	 * @author wujunyuan
	 * @date 2018年12月17日  下午2:33:42
	 * @param json 购物车json数据
	 * @param userId 用户id
	 * @return
	 */
	@Override
	public Map<String, Object> addShoppingcart(String shoppingcartJson,String userId) {
		// 校验userId
		if (StringUtils.isBlank(userId)) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_ERROR, "userid error");
		}
		// 校验json数据
		if (StringUtils.isBlank(shoppingcartJson)) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_ERROR);
		}

		// 将json数据转换成对象
		Shoppingcart shoppingcart = JSON.parseObject(shoppingcartJson, Shoppingcart.class);
		if (shoppingcart == null) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_ERROR);
		}
		// 校验添加的数据
		Map<String, Object> check = this.checkShoppingcart(shoppingcart);
		if (check != null) {
			return check;
		}
		// 设置用户id
		shoppingcart.setUserid(userId);
		//设置商品价格(与商品表同步)
		Map<String,Object> map = goodsMapper.findGoodsPrice(shoppingcart.getGoodsid());
		
		Object price = map.get("price");
		Object categoryId = map.get("categoryId");
		Object pic = map.get("pic");
		//分类判断
		if(categoryId==null||StringUtils.isBlank(categoryId.toString())) {
			return ResponseUtil.ajaxCheckError(ResultMessage.THIS_GOODS_NOT_CATEGORY,"categoryId is null~");
		}else {
			shoppingcart.setCategoryid((Long)categoryId);
		}
		
		//分类比例判断.
		//获取比例
		CategoryRatio categoryRatio = new CategoryRatio();
		categoryRatio.setCategoryid((Long)map.get("categoryId"));
		categoryRatio = categoryRatioMapper.selectOne(categoryRatio);
		if(categoryRatio==null) {
			return ResponseUtil.ajaxCheckError(ResultMessage.CATEGORY_RATIO_ERROR);
		}
		if(categoryRatio.getTraderratio()==null||categoryRatio.getAgentratio()==null
				||StringUtils.isBlank(categoryRatio.getTraderratio())
				||StringUtils.isBlank(categoryRatio.getAgentratio())) {
			return ResponseUtil.ajaxCheckError(ResultMessage.CATEGORY_RATIO_ERROR);
		}
		
		if(price!=null&&pic!=null) {
			shoppingcart.setPrice(map.get("price").toString());
			shoppingcart.setPic(map.get("pic").toString());
		}
		// 设置时间
		shoppingcart.setCreateTime(new Date());
		shoppingcart.setUpdateTime(new Date());
		//判断商品是否已存在数据库
		Shoppingcart isShoppingcart = new Shoppingcart();
		isShoppingcart.setUserid(shoppingcart.getUserid());
		isShoppingcart.setGoodsid(shoppingcart.getGoodsid());
		 List<Shoppingcart> list = shoppingcartMapper.select(isShoppingcart);
		if(list!=null&&list.isEmpty()) {
			// 将数据插入到数据库
			shoppingcartMapper.insertSelective(shoppingcart);
		}else {
			Shoppingcart shoppingcartUpdate = list.get(0);
			shoppingcartUpdate.setCount(shoppingcartUpdate.getCount()+shoppingcart.getCount());
			shoppingcartUpdate.setUpdateTime(new Date());
			// 将数据更新到数据库
			shoppingcartMapper.updateByPrimaryKeySelective(shoppingcartUpdate);
		}
		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK);
	}
	
	/**
	 * 校验添加的数据
	 * @author wujunyuan
	 * @date 2018年12月17日  下午2:29:03
	 * @param shoppingcart
	 * @return
	 */
	private Map<String, Object> checkShoppingcart(Shoppingcart shoppingcart) {
		if(StringUtils.isBlank(shoppingcart.getGoodsid())) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_ERROR,"goodsid error");
		}
		if(StringUtils.isBlank(shoppingcart.getTitle())) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_ERROR,"title error");
		}
		if(shoppingcart.getCount()==null||shoppingcart.getCount()<0) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_ERROR,"count error");
		}
		return null;
	}



	/**
	 * 查看购物车列表
	 * @author wujunyuan
	 * @date 2018年12月17日  下午3:20:21
	 * @param pageStart
	 * @param pageTotal
	 * @param userId 用户id
	 * @return
	 */
	@Override
	public Map<String, Object> findShoppingcartList(Long pageStart, Long pageTotal,String userId) {
		//校验参数
		if(userId==null) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_ERROR,"userId is null");
		}
		//初始化参数
		pageStart = PageUtils.initialPageStart(pageStart);
		pageTotal = PageUtils.packagePageTotal(pageTotal, 5, 10);
		//获取总记录数
		Long pageCount = shoppingcartMapper.countShoppingcartByuserId(userId);
		//获取购物车列表
		List<Map<String,Object>> data = shoppingcartMapper.findShoppingcartList(userId,
				PageUtils.countPageStart(pageStart, pageTotal),pageTotal);
		//处理图片
		if(data!=null&&!data.isEmpty()) {
			for (Map<String, Object> map : data) {
				Object pic = map.get("pic");
				if(pic!=null&&StringUtils.isNotBlank(pic.toString())) {
					map.put("pic", this.getPic(pic.toString()));
				}
			}
		}
		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK, new PageResponse(pageStart, pageTotal, pageCount, data));
	}

	/**
	 * 修改购物车商品数量
	 * @author wujunyuan
	 * @date 2018年12月20日  下午2:37:26
	 * @param request
	 * @param shoppingcartId 购物车id
	 * @param count 商品数量
	 * @return
	 * @throws Exception
	 */
	@Override
	public Map<String, Object> editShoppingcarCount(Long shoppingcartId, Integer count) {
		//校验参数
		if(shoppingcartId==null||shoppingcartId<=0) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_ERROR, "shoppingcartId error");
		}
		if(count==null||count<=0) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_ERROR, "count error");
		}
		//根据购物车id修改商品数量
		Shoppingcart shoppingcart = new Shoppingcart();
		shoppingcart.setId(shoppingcartId);
		shoppingcart.setCount(count);
		shoppingcartMapper.updateByPrimaryKeySelective(shoppingcart);
		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK);
	}

	/**
	 * 移除出购物车
	 * @author wujunyuan
	 * @date 2018年12月17日  下午4:22:58
	 * @param userId 用户id
	 * @param ids 购物车id数组
	 * @return
	 */
	@Override
	public Map<String, Object> removeShoppingcart(User user, String idJson) {
		// 校验数据
		if (StringUtils.isBlank(idJson)) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_NULL, "idJson is null~");
		}

		// 清空购物车
		if (idJson.equals("-1")) {
			Shoppingcart shoppingcart = new Shoppingcart();
			shoppingcart.setUserid(user.getId());
			shoppingcartMapper.delete(shoppingcart);
		} else {
			// 移除出购物车
			List<String> ids = JSON.parseArray(idJson, String.class);
			for (String id : ids) {
				if (StringUtils.isNotBlank(id)) {
					shoppingcartMapper.deleteByPrimaryKey(Long.parseLong(id));
				}
			}
		}
		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK);
	}

	/**
	 * 结算
	 * @author wujunyuan
	 * @date 2018年12月19日 下午2:19:02
	 * @param user
	 * @return
	 */
	@Override
	public Map<String, Object> settlement(User user) {
		//校验参数
		if(user==null) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_ERROR,"user is null");
		}
		//页面数据结果集
		Map<String, Object> resultMap  = new HashMap<>();
		
		Address address=new Address();
		address.setUserid(user.getId());
		address.setDefaultaddress(1);
		List<Address> addressList=addressMapper.select(address);
		if(addressList!=null && !addressList.isEmpty()) {
			//收货地址
			resultMap.put("address",addressList.get(0));
		}
		
		//获取购物车商品列表
		List<Map<String,Object>> goodsList = shoppingcartMapper.findShoppingcartList2(user.getId());
		
		//设置结算总价
		Map<String, Object> check = this.settingSettlementMoney(resultMap,goodsList);
		if(check!=null) {
			return check;
		}
//		resultMap.put("goodsList", goodsList);//商品列表
		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK, resultMap);
	}
	
	/**
	 * 设置结算总价
	 * @author chenluqiang
	 * @date 2019年1月18日 上午10:02:48 
	 * @param resultMap
	 * @param goodsList 
	 */
	private Map<String,Object> settingSettlementMoney(Map<String, Object> resultMap, List<Map<String, Object>> goodsList) {
		//订单总价
		String totalPrice="0";
		//产品总数
		String totalCount="0";
		//代理商总结算价
		String agentTotalPrice ="0";
		//分销商总结算价
		String traderTotalPrice="0";
		//电工安装补助金额
		String subsidy = "0";
		
		Map<String,Map<String,Object>> allMap = new HashMap<String,Map<String,Object>>();
		//
		CategoryRatio categoryRatio = null;
		if(goodsList!=null&&!goodsList.isEmpty()) {
			for (Map<String, Object> map : goodsList) {
				if(map.get("categoryId")==null||StringUtils.isBlank(map.get("categoryId").toString())) {
					return ResponseUtil.ajaxCheckError(ResultMessage.GOODS_HAS_PLACE,"categoryId is null~~");
				}
				//获取比例
				categoryRatio = new CategoryRatio();
				categoryRatio.setCategoryid((Long)map.get("categoryId"));
				categoryRatio = categoryRatioMapper.selectOne(categoryRatio);
				if(categoryRatio==null) {
					return ResponseUtil.ajaxCheckError(ResultMessage.CATEGORY_RATIO_ERROR);
				}
				if(categoryRatio.getTraderratio()==null||categoryRatio.getAgentratio()==null
						||StringUtils.isBlank(categoryRatio.getTraderratio())
						||StringUtils.isBlank(categoryRatio.getAgentratio())
						||StringUtils.isBlank(categoryRatio.getElectricratio())) {
					return ResponseUtil.ajaxCheckError(ResultMessage.CATEGORY_RATIO_ERROR);
				}
				
				//处理图片
				Object pic = map.get("pic");
				if(pic!=null&&StringUtils.isNotBlank(pic.toString())) {
					map.put("pic", this.getPic(pic.toString()));
				}
				
				//商品总价=商品数量*商品价格
				if(map.get("count")!=null&&StringUtils.isNotBlank(map.get("count").toString())
						&&map.get("price")!=null
						&&StringUtils.isNotBlank(map.get("price").toString())) {
					
					String goodsPrice = MathUtils.multiply(map.get("count").toString(), map.get("price").toString());
//					String agentPrice = MathUtils.multiply(categoryRatio.getAgentratio(),goodsPrice);
//					String traderPrice = MathUtils.multiply(categoryRatio.getTraderratio(),goodsPrice);
					//单品 价格 * 比例 
					String oneSubsidy = MathUtils.multiply(categoryRatio.getElectricratio(),goodsPrice);
					//合计比例价格
					agentTotalPrice=MathUtils.add(agentTotalPrice, goodsPrice);
					traderTotalPrice=MathUtils.add(traderTotalPrice, goodsPrice);
					subsidy=MathUtils.add(subsidy, oneSubsidy);
					
					totalPrice=MathUtils.add(totalPrice, goodsPrice);
					totalCount=MathUtils.add(map.get("count").toString(), totalCount);
				}
				
				//map
				if(map.get("categoryId")==null||StringUtils.isBlank(map.get("categoryId").toString())){
					return ResponseUtil.ajaxCheckError(ResultMessage.THIS_GOODS_NOT_CATEGORY,"categoryId is null~");
				}	
				//小类
				Map<String,Object> categoryMap =categoryMapper.getCategoryByCategoryId
							(Integer.parseInt(map.get("categoryId").toString()));
				if(categoryMap==null||categoryMap.isEmpty()||
						categoryMap.get("parentName")==null || StringUtils.isBlank(categoryMap.get("parentName").toString())) {
					return ResponseUtil.ajaxCheckError(ResultMessage.THIS_GOODS_NOT_LARGECATEGORY,"categoryMap is null~");
				}
				//拼接
				StringBuffer sb = new StringBuffer();
				sb.append(categoryMap.get("parentName").toString());
				sb.append("-");
				sb.append(categoryMap.get("categoryName").toString());
				
				categoryMap.put("nCategoryName", sb.toString());
				
				allMap.put(sb.toString(),categoryMap);
			}
			
			agentTotalPrice = MathUtils.multiply(categoryRatio.getAgentratio(),agentTotalPrice);
			traderTotalPrice = MathUtils.multiply(categoryRatio.getTraderratio(),traderTotalPrice);
			
			
			//整理返回格式
			for(Map<String,Object> categoryMap:allMap.values()) {
				List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
				for (Map<String, Object> map : goodsList) {
					if(categoryMap.get("categoryId").toString().equals(map.get("categoryId").toString())) {
						list.add(map);
					}
				}
				categoryMap.put("goods",list);
				//小计金额
				String minMoney = "0";
				//型号
				String number = "0";
				
				for(Map<String,Object> map :list) {
					String goodsPrice = MathUtils.multiply(map.get("count").toString(), map.get("price").toString());
					minMoney = MathUtils.add(minMoney, goodsPrice);
					number = MathUtils.add("1", number);
				}
				categoryMap.put("minMoney",minMoney);
				categoryMap.put("number",number);
				
				categoryMap.remove("parentName");
				categoryMap.remove("categoryName");
			}
			
			//加钱
			if(StringUtils.isNotBlank(agentTotalPrice)
					&&agentTotalPrice.indexOf(".")!=-1
					&&!agentTotalPrice.substring(agentTotalPrice.indexOf(".")+2).equals("")) {
				//加1分钱
				agentTotalPrice = MathUtils.add(agentTotalPrice, "0.01");
			}
			
			resultMap.put("subsidy", subsidy);
			resultMap.put("traderPrice", traderTotalPrice);// 分销商结算总价
			resultMap.put("agentPrice", agentTotalPrice);// 代理商结算总价
			resultMap.put("totalPrice", totalPrice);//订单总价
			resultMap.put("totalCount", totalCount);//产品总数
			
			resultMap.put("categorys", allMap.values());//
		}
		return null;
	}

	/**
	 * 提交订单
	 * @author wujunyuan
	 * @date 2018年12月18日  上午10:00:47
	 * @param request
	 * @param orderJson 订单json数据
	 * @param shoppingcartIds 购物车id数组
	 * @param electricianId 关联电工id
	 * @param shoppingJson 物流Json数据
	 * @return 
	 * @throws Exception
	 */
	@Override
	public Map<String, Object> submitOrder(User user,String orderJson,String shoppingcartIds
												,String shoppingJson,String electricianId) throws Exception {
		//校验参数
		if(user==null) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_NULL,"user is null");
		}
		if(StringUtils.isBlank(orderJson)) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_NULL,"orderJson is null~");
		}
		if(StringUtils.isBlank(shoppingJson)) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_NULL,"shoppingJson is null~");
		}
		if(StringUtils.isBlank(shoppingcartIds)) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_NULL,"shoppingcartIds is null~");
		}
		if(user.getType()!= 3 && StringUtils.isBlank(electricianId)) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PLESE_SELECT_ELECTRIC,"electricianId  is null~");
		}
		//将json数据转换成对象
		Order order = JSON.parseObject(orderJson, Order.class);
		Shipping shopping = JSON.parseObject(shoppingJson,Shipping.class);
		//校验订单添加的数据
		Map<String,Object> checkOrder = this.checkOrder(order);
		if(checkOrder!=null) {
			return checkOrder;
		}
		// 校验物流添加的数据
		Map<String, Object> checkShopping = this.checkShopping(shopping);
		if (checkShopping != null) {
			return checkShopping;
		}
		
		//关联电工信息
		User linkUser = null;
		if(user.getType()==3) { //电工提交
			//获取用户层级关系
			URoleLevel uRoleLevel = uRoleLevelMapper.selectByPrimaryKey(user.getId());
			
			if(uRoleLevel==null) {
				return ResponseUtil.ajaxCheckError(ResultMessage.USER_ISNOT_EXITS,"uRoleLevel is null~");
			}
			
			String topLevelId = null;
			if(StringUtils.isBlank(uRoleLevel.getTraderid())) { //上级是代理商
				topLevelId = uRoleLevel.getAgentid();
			}else { 											//上级是分销商
				topLevelId = uRoleLevel.getTraderid();
			}
			//校验数据的正确性
			if(user.getId().equals(topLevelId)) {
				return ResponseUtil.ajaxCheckError(ResultMessage.PLESE_LOGIN);
			}
			
			//设置电工上级地址
			Address userAddress = new Address();
			userAddress.setUserid(topLevelId);
			userAddress.setDefaultaddress(1);  //默认地址
			
			//设置电工地址
			shopping.setElectricaddress(shopping.getAddress());
			shopping.setElectricname(shopping.getAddressee());
			shopping.setElectricphone(shopping.getAddresseephone());
			
			//获取上级地址
			List<Address> userAddressList = addressMapper.select(userAddress);
			if(userAddressList==null||userAddressList.size()==0) {
				 return ResponseUtil.ajaxCheckError(ResultMessage.ADDRESS_NOT_EXITS,"user address is error!");
			}
			userAddress = userAddressList.get(0);
			//设置上级信息
			shopping.setAddress(
					userAddress.getProvince()+userAddress.getCity()+userAddress.getArea()+userAddress.getAddress());
			shopping.setAddressee(userAddress.getName());
			shopping.setAddresseephone(userAddress.getPhone());
			
			linkUser = user;
		}else {
			//设置关联电工地址信息
			Address linkAddress = new Address();
			//设置关联电工地址
			linkAddress.setUserid(electricianId);
			linkAddress.setDefaultaddress(1);
			List<Address> linkUserAddress = addressMapper.select(linkAddress);
			if(user.getType() !=3 && linkUserAddress!=null&&!linkUserAddress.isEmpty()) {
				linkAddress = linkUserAddress.get(0);
				//设置关联电工信息
				shopping.setElectricaddress(linkAddress.getAddress());
				shopping.setElectricname(linkAddress.getName());
				shopping.setElectricphone(linkAddress.getPhone());
			}else {
				return ResponseUtil.ajaxCheckError(ResultMessage.ELEC_ADDRESS_NOT_EXITS,"electric address is error!");
			}
			
			linkUser = userMapper.selectByPrimaryKey(electricianId);
		}
		
		//添加数据并插入到物流表
		this.setShoppingData(user, shopping);
		
		//加数据并插入到订单表
		this.setOrderData(user,order,linkUser,shopping);	
		
		//加数据并插入到o_role_level表
		ORoleLevel oRoleLevel = new ORoleLevel();
		this.setORoleLevelData(user,order,oRoleLevel,linkUser.getId());
		
		//添加数据并插入到o_order_item表
		OrderItem orderItem = new OrderItem();
		Map<String, Object> check = this.setOrderItemData(order,shoppingcartIds,orderItem,shopping);
		if(check!=null) {
			return check;
		}
		
		//加数据并插入到o_process表
		Process process = new Process();
		this.setProcessData(user,order,process,oRoleLevel);
		
		//加数据并插入到u_message表
		Message message =  new Message();
		this.setMessageData(user,message);
		
		//任务调度记录订单id
		Quartz quartz = new Quartz();
		quartz.setId(UUID.randomUUID().toString().replaceAll("-",""));
		quartz.setBusinessid(order.getId());
		quartz.setKeyword(ResultMessage.QUARTZ_KEYWORD);
		quartz.setCreateTime(new Date());
		quartz.setUpdateTime(new Date());
		quartzMapper.insertSelective(quartz);
		
		//结果集
		Map<String,Object> resultMap = new HashMap<>();
		//返回订单编号
		resultMap.put("ordernum", order.getOrdernum());
		//返回订单金额
		resultMap.put("price", order.getPaymentprice());
		//返回订单id
		resultMap.put("orderId", order.getId());
		
		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK,resultMap);
	}


	/**
	 * 加数据并插入到u_message表
	 * @author wujunyuan
	 * @date 2019年1月8日  下午2:18:15
	 * @param user
	 * @param message
	 */
	private void setMessageData(User user, Message message) {
		message.setId(UUID.randomUUID().toString().replace("-", ""));
		message.setCreateTime(new Date());
		message.setUpdateTime(new Date());
		message.setType(2);
		message.setIsRead(0); //未读状态
		message.setTitle("订单通知");
		message.setContent("您收到一个新订单,快去看看吧!");
		message.setUserid(user.getUserParentId());
		messageMapper.insertSelective(message);
	}

	/**
	 * 校验物流添加的数据
	 * @author wujunyuan
	 * @date 2018年12月21日  上午9:29:02
	 * @param shopping
	 * @return
	 */
	private Map<String, Object> checkShopping(Shipping shopping) {
		// 收件人姓名
		if (StringUtils.isBlank(shopping.getAddressee())) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_ERROR, "addressee error");
		}
		// 收件人电话
		if (StringUtils.isBlank(shopping.getAddresseephone())) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_ERROR, "addresseephone error");
		}
		// 收货地址
		if (StringUtils.isBlank(shopping.getAddress())) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_ERROR, "address error");
		}
		return null;
	}


	/**
	 * 加数据并插入到o_role_level表
	 * @author wujunyuan
	 * @date 2018年12月21日  上午10:44:41
	 * @param user
	 * @param order
	 */
	private void setORoleLevelData(User user, Order order,ORoleLevel oRoleLevel,String linkUserId) {
		oRoleLevel.setOrderid(order.getId());
		
		//查询该用户的层级关系
		URoleLevel uRoleLevel = uRoleLevelMapper.selectByPrimaryKey(user.getId());
		if(user.getType()==3) {//电工
			oRoleLevel.setElectid(user.getId());
			if(uRoleLevel!=null) {
				oRoleLevel.setAgentid(uRoleLevel.getAgentid());
				oRoleLevel.setTraderid(uRoleLevel.getTraderid());
//				 消息推送给分销商
				User Trader = userMapper.selectByPrimaryKey(uRoleLevel.getTraderid());
				JpushClientUtil.initJPushClient(ResultMessage.JGTSKEY, ResultMessage.JGTSECRET);
				if(Trader!=null&&StringUtils.isNoneBlank(Trader.getRegistrationId())) {
					JpushClientUtil.sendToRegistrationId(Trader.getRegistrationId(), "订单通知", "订单通知", "您收到一个新订单,快去看看吧!", "", "", "", new HashMap<>());
				}
//				 消息推送给分销商
				User Agent = userMapper.selectByPrimaryKey(uRoleLevel.getAgentid());
				JpushClientUtil.initJPushClient(ResultMessage.JGTSKEY, ResultMessage.JGTSECRET);
				if(Agent!=null&&StringUtils.isNoneBlank(Agent.getRegistrationId())) {
					JpushClientUtil.sendToRegistrationId(Agent.getRegistrationId(), "订单通知", "订单通知", "您收到一个新订单,快去看看吧!", "", "", "", new HashMap<>());
				}
			}
		}else if(user.getType()==2){//分销商
			oRoleLevel.setElectid(linkUserId);
			oRoleLevel.setTraderid(user.getId());
			oRoleLevel.setAgentid(uRoleLevel.getAgentid());
//			 消息推送给代理商
			User Agent = userMapper.selectByPrimaryKey(uRoleLevel.getAgentid());
			JpushClientUtil.initJPushClient(ResultMessage.JGTSKEY, ResultMessage.JGTSECRET);
			if(Agent!=null&&StringUtils.isNoneBlank(Agent.getRegistrationId())) {
				JpushClientUtil.sendToRegistrationId(Agent.getRegistrationId(), "订单通知", "订单通知", "您收到一个新订单,快去看看吧!", "", "", "", new HashMap<>());
			}
//			 消息推送给电工
			User linkUser = userMapper.selectByPrimaryKey(linkUserId);
			JpushClientUtil.initJPushClient(ResultMessage.JGTSKEY, ResultMessage.JGTSECRET);
			if(linkUser!=null&&StringUtils.isNoneBlank(linkUser.getRegistrationId())) {
				JpushClientUtil.sendToRegistrationId(linkUser.getRegistrationId(), "订单通知", "订单通知", "您收到一个新订单,快去看看吧!", "", "", "", new HashMap<>());
			}
		}else if(user.getType()==1) { //代理商
			oRoleLevel.setAgentid(user.getId());
			oRoleLevel.setElectid(linkUserId);
//			 消息推送给电工
			User linkUser = userMapper.selectByPrimaryKey(linkUserId);
			JpushClientUtil.initJPushClient(ResultMessage.JGTSKEY, ResultMessage.JGTSECRET);
			if(linkUser!=null&&StringUtils.isNoneBlank(linkUser.getRegistrationId())) {
				JpushClientUtil.sendToRegistrationId(linkUser.getRegistrationId(), "订单通知", "订单通知", "您收到一个新订单,快去看看吧!", "", "", "", new HashMap<>());
			}
		}
		
		oRoleLevelMapper.insertSelective(oRoleLevel);
	}

	/**
	 * 加数据并插入到o_role_level表
	 * @author wujunyuan
	 * @date 2018年12月21日  上午10:44:41
	 * @param user
	 * @param order
	 */
	/*private void setORoleLevelData(User user, Order order,ORoleLevel oRoleLevel) {
		oRoleLevel.setOrderid(order.getId());
		
		//查询该用户的层级关系
		URoleLevel uRoleLevel = uRoleLevelMapper.selectByPrimaryKey(user.getId());
		if(user.getType()==3) {//电工
			oRoleLevel.setElectid(user.getId());
			if(uRoleLevel!=null) {
				oRoleLevel.setAgentid(uRoleLevel.getAgentid());
				oRoleLevel.setTraderid(uRoleLevel.getTraderid());
			}
		}else if(user.getType()==2){//分销商
			oRoleLevel.setTraderid(user.getId());
			oRoleLevel.setAgentid(uRoleLevel.getAgentid());
		}else if(user.getType()==1) { //代理商
			oRoleLevel.setAgentid(user.getId());
		}
		
		oRoleLevelMapper.insertSelective(oRoleLevel);
	}*/


	/**
	 * 加数据并插入到o_process表
	 * @author wujunyuan
	 * @date 2018年12月19日  下午6:21:01
	 * @param order
	 * @param process
	 * @param oRoleLevel 
	 */
	private void setProcessData(User user, Order order, Process process, ORoleLevel oRoleLevel) {
		process.setId(UUID.randomUUID().toString().replace("-", ""));
		process.setOrderid(order.getId());
		//订单流程状态 
		// 0=电工申请 1=分销商申请 2=代理商申请 3=分销商待审核 4=分销商审核不通过 
	//5=代理商待审核 6=代理商审核不通过 7=厂家待批准 8=厂家批准不通过 9=厂家待发货  10=分销/代理待收货  11=完成 
		switch (user.getType()) {
		case 1://代理商
			process.setStatus(5);
			break;
		case 2://分销商
			process.setStatus(5);
			break;
		case 3://电工
			//上级是分销商
			if(oRoleLevel.getAgentid()!=null&&oRoleLevel.getTraderid()!=null) {
				process.setStatus(3);
			}
			//上级是代理商
			if(oRoleLevel.getAgentid()!=null&&oRoleLevel.getTraderid()==null){
				process.setStatus(5);
			}
			break;
		}
		//是否取消订单 0=否 1=是
		process.setIscancel(0);
		//提交申请时间
		process.setPosttime(new Date());
		process.setCreateTime(new Date());
		process.setUpdateTime(new Date());
		//是否能申请售后 0=否 1=是
		process.setIsRefund(0);
		processMapper.insertSelective(process);
	}



	/**
	 * 添加数据并插入到o_order_item表
	 * @author wujunyuan
	 * @date 2018年12月19日  下午5:53:56
	 * @param user
	 * @param order
	 * @param goodsIds
	 * @param orderItem
	 * @param shopping
	 */
	private Map<String,Object> setOrderItemData(Order order, String shoppingcartIds, OrderItem orderItem, Shipping shopping) {
		
		List<String> shoppingcartIds2 = JSON.parseArray(shoppingcartIds,String.class);
		
		//校验购物车数据
		if(shoppingcartIds2==null||shoppingcartIds2.isEmpty()) {
			return ResponseUtil.ajaxCheckError(ResultMessage.SHOPPINGCART_IS_NOTNULL);
		}
		
		for (String id : shoppingcartIds2) {
			if(!CheckUtil.checkIsNumber(id)) {
				return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_ERROR,"shoppingcartIds is error~");
			}
			Shoppingcart shoppingcart = shoppingcartMapper.selectByPrimaryKey(Long.parseLong(id));
			if(shoppingcart==null) {
				return ResponseUtil.ajaxCheckError(ResultMessage.GOODS_HAS_PLACE,"shoppingcart is null~");
			}
			orderItem.setId(UUID.randomUUID().toString().replace("-", ""));
			//商品id
			orderItem.setGoodsid(shoppingcart.getGoodsid());
			//获取商品分类
			if(shoppingcart.getCategoryid()==null
					||StringUtils.isBlank(shoppingcart.getCategoryid().toString())) {
				return ResponseUtil.ajaxCheckError(ResultMessage.THIS_GOODS_NOT_CATEGORY,"categoryId is null~");
			}
			orderItem.setCategoryid(shoppingcart.getCategoryid());
			
			//获取比例
			CategoryRatio categoryRatio = new CategoryRatio();
			categoryRatio.setCategoryid(shoppingcart.getCategoryid());
			categoryRatio = categoryRatioMapper.selectOne(categoryRatio);
			if(categoryRatio==null) {
				return ResponseUtil.ajaxCheckError(ResultMessage.CATEGORY_RATIO_ERROR);
			}
			if(StringUtils.isBlank(categoryRatio.getTraderratio())
					||StringUtils.isBlank(categoryRatio.getAgentratio())
					||StringUtils.isBlank(categoryRatio.getElectricratio())
					) {
				return ResponseUtil.ajaxCheckError(ResultMessage.CATEGORY_RATIO_ERROR);
			}
			orderItem.setAgentratio(categoryRatio.getAgentratio());
			orderItem.setElectricratio(categoryRatio.getElectricratio());
			orderItem.setTraderratio(categoryRatio.getTraderratio());
			
			//订单id
			orderItem.setOrderid(order.getId());
			//商品标题
			orderItem.setGoodstitle(shoppingcart.getTitle());
			//商品图片路径
			orderItem.setGoodspic(shoppingcart.getPic());
			//商品价格 
			orderItem.setGoodsprice(shoppingcart.getPrice());
			//商品购买的数量
			orderItem.setGoodscount(shoppingcart.getCount().toString());
			
			orderItem.setCreateTime(new Date());
			orderItem.setUpdateTime(new Date());
			
			orderItemMapper.insertSelective(orderItem);
			
			//清空购物车
			shoppingcartMapper.delete(shoppingcart);
		}
		return null;
	}



	/**
	 * 添加数据到物流表
	 * @author wujunyuan
	 * @date 2018年12月19日  下午5:46:42
	 * @param user
	 * @param order
	 * @param shopping 
	 */
	private void setShoppingData(User user,Shipping shopping) {
			shopping.setId(UUID.randomUUID().toString().replace("-", ""));
			shopping.setCreateTime(new Date());
			shopping.setUpdateTime(new Date());
			shoppingMapper.insertSelective(shopping);
	}



	/**
	 * 添加订单表数据
	 * 
	 * @author wujunyuan
	 * @date 2018年12月18日 下午2:53:07
	 * @param user
	 * @param order
	 * @param shopping 
	 * @throws Exception 
	 */
	private void setOrderData(User user,Order order,User linkUser, Shipping shopping) throws Exception {
		// 生成订单id
		order.setId(UUID.randomUUID().toString().replace("-", ""));
		// 设置用户id
		order.setUserid(user.getId());
		// 生成订单编号
		order.setOrdernum(NumberUtils.getOrderNumber(ResultMessage.ORDER_PREFIX, ResultMessage.ORDER_SUFFIX));
		//设置shippingId
		order.setShippingid(shopping.getId());
		// 设置订单创建人
		order.setUsername(user.getNickName());
		//设置关联人(一般为电工)
		order.setLinkname(linkUser.getNickName());
		order.setLinkuserid(linkUser.getId());
		
		//判断是否是代理商,其他的只能线下支付
		if(user.getType()==1) {
			order.setPaytype(null);
			// 待付款
			order.setPaystatus(2);
		}else {
			//线下支付
			order.setPaytype(0);
			// 未支付
			order.setPaystatus(0);
		}
		
		// 下单时间
		order.setPlacetime(new Date());
		order.setCreateTime(new Date());
		order.setUpdateTime(new Date());
		//插入到order表
		orderMapper.insertSelective(order);
	}



	/**
	 * 校验订单添加的数据
	 * @author wujunyuan
	 * @date 2018年12月18日  下午2:15:34
	 * @param order
	 * @return
	 */
	private Map<String, Object> checkOrder(Order order) {
		//实付金额
		if(StringUtils.isBlank(order.getPaymentprice())) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_ERROR,"paymentprice error");
		}
		if(order.getTraderprice().equals("0")) {
			return ResponseUtil.ajaxCheckError(ResultMessage.MONEY_NOT_0);
		}
		//代理商价格 
		if(StringUtils.isBlank(order.getAgentprice())){
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_ERROR,"agentPrice error");
		}
		//分销商价
		if (StringUtils.isBlank(order.getTraderprice())) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_ERROR, "traderPrice error");
		}
		if(order.getTraderprice().equals("0")) {
			return ResponseUtil.ajaxCheckError(ResultMessage.MONEY_NOT_0);
		}
		//订单总价(是根据商品数量X单价得出)单位元
		if(StringUtils.isBlank(order.getTotalprice())) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_ERROR,"totalprice error");
		}	
		if(order.getTotalprice().equals("0")) {
			return ResponseUtil.ajaxCheckError(ResultMessage.MONEY_NOT_0);
		}
		//购买商品的总数
		if (StringUtils.isBlank(order.getCount())) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_ERROR,"count error");
		}
		//校验安装补助
		if (StringUtils.isBlank(order.getGrants())) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_ERROR, "grants error");
		}
		return null;
	}

	/**
	 * 选择支付方式
	 * @author wujunyuan
	 * @date 2018年12月20日 上午10:28:44
	 * @param payType
	 * @return
	 */
	@Override
	public Map<String, Object> choosePayment(String orderNum,Integer payType) {
		//校验参数
		if(StringUtils.isBlank(orderNum)) {
			return ResponseUtil.ajaxCheckError(ResultMessage.CATEGORY_ID_ERROR);
		}
		if(payType<1||payType>2) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PAYTYPE_ERROR);
		}
		//根据订单编号获取订单
		Order order = new Order();
		order.setOrdernum(orderNum);
		Order newOrder = orderMapper.selectOne(order);
		//设置支付方式
		newOrder.setPaytype(payType);
		orderMapper.updateByPrimaryKeySelective(newOrder);
		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK);
	}
	
	/**
	 * 统计购物车商品数量和金额
	 * @author chenluqiang
	 * @date 2019年3月19日 下午4:50:14 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@Override
	public Map<String, Object> countShoppingCartMoney(User user) {
		Map<String,Object> result = new HashMap<String,Object>();
		String count = "0";
		String totalMoney = "0.00";
		int num = 0;
		//查询用户购物车
		List<Map<String, Object>> list = shoppingcartMapper.getShoppingCartMoneyAndNumByUserId(user.getId());
		if(list!=null&&!list.isEmpty()) {
			for(Map<String,Object> map : list) {
				if(map!=null&&!map.isEmpty()) {
					Object countObj =  map.get("count");
					Object priceObj= map.get("price");
					if(countObj!=null&&StringUtils.isNotBlank(countObj.toString())
							&&priceObj!=null&&StringUtils.isNotBlank(priceObj.toString())) {
						count = MathUtils.add(countObj.toString(), count);
						String temp =  MathUtils.multiply(countObj.toString(),priceObj.toString());
						totalMoney = MathUtils.add(temp, totalMoney);
					}
				}
			}
			num = list.size();
		}
		
		result.put("count",count);
		result.put("num",num);
		result.put("totalMoney",totalMoney);
		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK,result);
	}
	
}
